package com.mall.web.control.app.pay;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alipay.config.AlipayConfig;
import com.alipay.sign.RSA;
import com.mall.biz.pay.PayBizImpl;
import com.mall.client.mall.MallService;
import com.mall.client.trade.TradeService;
import com.mall.common.Consts.PayType;
import com.mall.common.Consts.tradeOrderType;
import com.mall.common.util.bit.PropertiesConfigure;
import com.mall.constant.PropertiesKey;
import com.mall.constant.TradeTypeConstant;
import com.mall.pojo.Mall;
import com.mall.pojo.Trade;
import com.mall.pojo.User;
import com.mall.web.annotation.UserSecurity;
import com.mall.web.control.app.result.MallResultController;
import com.mall.web.util.APPCookieUtil;
import com.mall.web.util.HttpUtil;
import com.mall.web.util.WebUtil;

@Controller
@RequestMapping("/pay/")
public class PayController {
	
	private static final Logger log = LoggerFactory.getLogger(PayController.class);
	@Autowired
	private TradeService tradeService;
	
	@Autowired
	private PropertiesConfigure propertiesConfigure; 
	@Autowired
	private  MallService mallService;
	@Autowired
	private PayBizImpl payBizImpl;
	
	@UserSecurity
	@RequestMapping("pay")
	public String pay(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap){
		Long orderId = HttpUtil.getLongValueFromRequest(request, "orderId");
		Trade trade = this.tradeService.getTradeByOrderId(orderId);
		Mall mall = this.mallService.getMallById(trade.getMallId());
		String mallName = mall.getMallName();
		
		String itemDesc = "";
		if(trade.getType()==tradeOrderType.TYPE_YOUHUI){
			itemDesc = mallName+"优惠买单";
		}else if(trade.getType()==tradeOrderType.TYPE_MALLGROUPBUY){
			itemDesc = mallName+"团购买单";
		}else if(trade.getType()==tradeOrderType.TYPE_ZHIHUI){
			itemDesc = mallName+"智慧餐厅买单";
		}else if(trade.getType()==tradeOrderType.TYPE_MINSU){
			itemDesc = mallName+"民宿买单";
		}else{
			itemDesc = mallName+"买单";
		}
		
		String returnURL = "";
		switch (trade.getType()) {
		case tradeOrderType.TYPE_ZHIHUI:case tradeOrderType.TYPE_MINSU:case tradeOrderType.TYPE_YOUHUI:
			returnURL = "/mallresult/success.htm?type=" + MallResultController.TRADE_TYPE + "&mallId=" + trade.getMallId()
					+"&price="+trade.getPrice();
			break;
		case tradeOrderType.TYPE_MALLGROUPBUY:
			returnURL = "/mallresult/success.htm?type=" + MallResultController.TUAN_TRADE_TYPE + "&mallId=" + trade.getMallId()
				+"&price="+trade.getPrice()+"&tuancode="+payBizImpl.TuanCodeAll(trade);
			break;
		
		}
		returnURL = propertiesConfigure.getProperties(PropertiesKey.httpbeginurl) +returnURL;
		String returnURLEncode = "";
		
		try {
			returnURLEncode  = URLEncoder.encode(returnURL, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String notifyURL = propertiesConfigure.getProperties(PropertiesKey.httpbeginurl) +"/aliPayApp/notify_url_app.htm";
		modelMap.put("notifyURL", notifyURL);
		modelMap.put("itemDesc", itemDesc);
		modelMap.put("returnURL", returnURL);
		modelMap.put("returnURLEncode", returnURLEncode);
		String referer = request.getHeader("Referer");
		modelMap.put("app", APPCookieUtil.urlFromApp(request));
		modelMap.put("referer", referer);
		modelMap.put("trade", trade);
		modelMap.put("mall", mall);
		
//		try {
//			modelMap.put("payforalipayEncodeStr", URLEncoder.encode(getOrderInfoByAliPay(trade, mall, itemDesc),"utf-8"));
//		} catch (UnsupportedEncodingException e) {
//			modelMap.put("payforalipayEncodeStr", getOrderInfoByAliPay(trade, mall, itemDesc));
//			System.out.println(e.getMessage());
//		}
		modelMap.put("payforalipayStr", getOrderInfoByAliPay(trade, mall, itemDesc));
		return "pay/pay";
		
	}
	
	@UserSecurity
	@RequestMapping("payAction")
	public String payAction(@RequestParam(required = true) Integer payType, @RequestParam(required = true) Long orderId,
			HttpServletRequest request, HttpServletResponse response){
		
		Trade trade = this.tradeService.getTradeByOrderId(orderId);
		if (trade == null) {
			log.error("订单错误");
			return null;
		}
		trade.setGmtModify(new Date());
		trade.setPayType(payType);// 支付方式1:微信;2支付宝
		this.tradeService.updateTradeByTrade(trade);
		switch (payType) {
		case PayType.WEIXIN: // 微信支付
			return "redirect:/wxPay/auth.htm?orderId=" + orderId;
		case PayType.ALIPAY: // 支付宝支付
			return "redirect:/aliPay/pay.htm?orderId=" + orderId;
		}
		return null;
		
	}
	
	

	/**
	 * 支付宝支付
	 * 
	 * @param orderId
	 *            订单编号
	 * @param actualPay
	 *            实际支付金额
	 * @return
	 */
	private String getOrderInfoByAliPay(Trade trade, Mall mall, String itemDesc) {
		// 回调页面
		String ali_call_back_url = propertiesConfigure.getProperties(PropertiesKey.httpbeginurl)
				+ "/aliPayApp/notify_url_app.htm";
		String seller_id = AlipayConfig.seller_id;// 商户编号
		String[] parameters = { "partner=\"" + seller_id + "\"", // 合作身份者ID（16位）
				"seller_id=\"" + seller_id + "\"", // 账户邮箱
				"out_trade_no=\"" + trade.getOutTradeNo() + "\"", // 商户内部订单号
				"subject=\"" + itemDesc + "\"", // 测试
				"body=\"" + itemDesc + "\"", // 订单说明
				"total_fee=\"" + "0.01" + "\"", // 支付金额（元）
				"notify_url=\"" + ali_call_back_url + "\"", // 通知地址
				"service=\"mobile.securitypay.pay\"", // 固定值（手机快捷支付）
				"payment_type=\"1\"", // 固定值
				"_input_charset=\"utf-8\"", "it_b_pay=\"30m\"", "&show_url=\"m.alipay.com\""// 通知地址
		};
		String signOrderUrl = signAllString(parameters);
		return signOrderUrl;
	}
	 
	 

	 /**
	  * 支付宝签名(给app签名）
	  * @param array
	  * @return
	  */
	 private String signAllString(String [] array){
	    StringBuffer sb = new StringBuffer("");
	    for (int i = 0; i < array.length; i++) {
	       if(i==(array.length-1)){
	          sb.append(array[i]);
	       }else{
	          sb.append(array[i]+"&");
	       }
	    }
	    String sign = "";
	    try {
	       sign = URLEncoder.encode(RSA.sign(sb.toString(), AlipayConfig.private_key, "utf-8"), "utf-8");//private_key私钥
	    } catch (UnsupportedEncodingException e) {
	       e.printStackTrace();
	    }
	    sb.append("&sign=\""+sign+"\"&");
	    sb.append("sign_type=\"RSA\"");
	    return sb.toString();
	 }
	
	
	 	@RequestMapping("zhongzhiSuccess")
		public String zhongzhiSuccess(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
			User user = WebUtil.getCurrentUser(request);
			if (user == null) {
				return null;
			}
			String tradeId = request.getParameter("tradeId");
			Trade trade = this.tradeService.getTradeByOrderId(Long.parseLong(tradeId));
			if (trade.getPayType() == 1) {
				return "redirect:/weishang/trade/orderSuccess.htm";
			}
			

			return null;

		}
	
}
